<template>
  <div class="ActivitySign">
    <div class="msg">
      <div class="item">
        <span class="label">
          <i class="iconfont iconshijian"></i>
          时间:
        </span>
        <span class="value">{{ formatDate(new Date, 'HH:mm') }}</span>
      </div>
      <div class="item">
        <span class="label">
          <i class="iconfont icondidian"></i>
          地点:
        </span>
        <span class="value">{{ address }}</span>
      </div>
    </div>
    <div class="map-warp">
      <map class="map" :longitude="longitude" :latitude="latitude" :markers="markers" :circles="circles" />
    </div>
    <div class="form" v-if="isSignOut">
      <CommonFormCreate ref="form" v-model="form" :options="options" />
    </div>
    <div class="footer">
      <div class="btn-wrap">
        <div
          v-if="isSignIn"
          class="btn"
          hover-class="hover"
          hover-start-time="0"
          hover-stay-time="0"
          @click="handleSignIn">签到</div>
        <div
          v-if="isSignOut"
          class="btn"
          hover-class="hover"
          hover-start-time="0"
          hover-stay-time="0"
          @click="handleSignOut">签退</div>
      </div>
    </div>
  </div>
</template>

<script>
import api from '@/api'
import { formatDate } from '@/utils'
import QQMapWX from '@/utils/qqmap-wx-jssdk.min'
import CommonModal from '@/components/CommonModal'
import dealAddress from '@/utils/dealAddress'
import wxp from '@/utils/wxp'
import TYPE from '@/components/CommonFormCreateType'
import CommonFormCreate from '@/components/CommonFormCreate'
import config from '@/config'

export default {
  components: {
    CommonModal,
    CommonFormCreate,
  },
  data () {
    return {
      dealAddress,
      formatDate,
      id: '',
      data: {},
      isFromCode: false,
      signInPhotoUrl: [],
      signOutPhotoUrl: [],
      latitude: '',
      longitude: '',
      markers: [],
      address: '',
      suggest: '',
      options: [
        {
          type: TYPE.IMG_UPLOAD,
          title: '附件',
          field: 'signPhoto',
        },
      ],
      form: {
        signPhoto: '',
      },
    }
  },
  computed: {
    isSignIn () {
      if (this.data.nextNode) {
        return this.data.nextNode.some(item => parseInt(item.code) === 5)
      } else {
        return false
      }
    },
    isSignOut () {
      if (this.data.nextNode) {
        return this.data.nextNode.some(item => parseInt(item.code) === 7)
      } else {
        return false
      }
    },
    circles () {
      return [{
        latitude: this.data.latitude,
        longitude: this.data.longitude,
        radius: parseInt(this.data.signDistance) || 500,
        color: '#99c8f8',
        fillColor: '#2222221e',
        strokeWidth: 1,
      }]
    },
  },
  onLoad (options) {
    this.id = options.id
    this.isFromCode = options.isFromCode
    this.getData()
  },
  onShow () {
    this.authLocation()
  },
  methods: {
    async getData () {
      const { result } = await api.getActivityDetail({ id: this.id })
      this.data = result
    },
    async authLocation () {
      const res = await wxp.getSetting()
      if (!res.authSetting['scope.userLocation']) {
        try {
          await wxp.authorize({
            scope: 'scope.userLocation',
          })
          this.getLocation()
        } catch (e) {
          const res = await wxp.showModal({
            title: '温馨提示',
            content: '需要授权地理位置才能进行签到签退，请去设置打开',
            showCancel: false,
          })
          if (res.confirm) {
            const res = await wxp.openSetting()
            res.authSetting = {
              'scope.userLocation': true,
            }
          }
        }
      } else {
        this.getLocation()
      }
    },
    getLocation () {
      wx.getLocation({
        type: 'gcj02',
        success: res => {
          this.latitude = res.latitude
          this.longitude = res.longitude
          this.markers = [{
            id: 0,
            latitude: this.latitude,
            longitude: this.longitude,
          }]
          this.getAddress([this.longitude, this.latitude])
        },
        fail () {
          uni.showModal({
            title: '定位失败',
            content: '请退出重试',
            showCancel: false,
          })
        },
      })
    },
    async getAddress (position) {
      const qqmapsdk = new QQMapWX({ key: config.qqMapKey })
      await qqmapsdk.reverseGeocoder({
        location: position.reverse().join(','),
        success: res => {
          if (res.status === 0) {
            this.address = `${res.result.address_component.city} • ${res.result.formatted_addresses.recommend}`
          } else {
            console.log('获取地址失败', res)
          }
        },
        fail (res) {
          console.log('获取地址失败', res)
        },
      })
    },
    async handleSignIn () {
      await api.activityNext({
        activityId: this.data.activityId,
        joinId: this.data.joinId,
        nextStepCode: '05',
        latitude: String(this.latitude),
        longitude: String(this.longitude),
      })
      uni.navigateBack()
      uni.showModal({
        title: '成功',
        content: `谢谢！您在“${this.data.title}”的签到操作已经成功！`,
        showCancel: false,
        success (res) {
          if (res.confirm) {
            uni.navigateBack()
          }
        },
      })
    },
    async handleSignOut () {
      await api.activityNext({
        activityId: this.data.activityId,
        joinId: this.data.joinId,
        nextStepCode: '07',
        latitude: String(this.latitude),
        longitude: String(this.longitude),
        signPhoto: this.form.signPhoto,
      })
      uni.showModal({
        title: '成功',
        content: `谢谢！您在“${this.data.title}”的签退操作已经成功！`,
        showCancel: false,
        success (res) {
          if (res.confirm) {
            uni.navigateBack()
          }
        },
      })
    },
  },
}
</script>

<style lang="scss" scoped> @import "~css/var.scss";

.ActivitySign {
	.msg {
		padding: 16px;
		font-size: $fz-m;
		background: #fff;

		.item {
			display: flex;
			margin-top: 5px;

			.label {
				display: flex;
				align-items: center;
				flex: 0 0 60px;
				color: #222;
			}

			.value {
				color: #333;
			}
		}
	}

	.map-warp {
		.map {
			width: 700rpx;
			height: 500rpx;
			margin: 24px auto;
		}
	}

	.form {
		box-sizing: border-box;
		width: 700rpx;
		margin: 24px auto;
		padding: 10px;
		border-radius: 5px;
		background: #fff;
	}

	.tip {
		text-align: center;
		font-size: $fz-s;
		color: #333;
	}

	.footer {
		display: flex;

		.btn-wrap {
			flex: 1;

			.btn {
				margin: 25px 10px;
				border: 1px solid transparent;
				border-radius: 5px;
				line-height: 46px;
				text-align: center;
				font-weight: 500;
				font-size: $fz-l;
				color: #fff;
				background: #d1272f;

				&.hover {
					opacity: .8;
				}

				&.status {
					border: 1px solid #d1272f;
					color: #d1272f;
					background: #fff;
				}
			}
		}
	}
}
</style>
